package com.zwps.common.core.mybatis.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;

import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;

import com.zwps.common.api.model.vo.LoginInfoVO;
import com.zwps.common.core.context.LoginInfoContext;
import com.zwps.common.mybatis.plus.interceptor.CommonDataPermissionInterceptor;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

/**
 * 注入指定部门下的用户ID列表，通过ID列表查询条件实现权限过滤
 * 
 * @ClassName: DeptScopeDataFilterInterceptor
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author lyh
 * @date 2023年5月26日 下午3:46:17
 *
 */
public class DeptScopeDataInterceptor extends CommonDataPermissionInterceptor {

    public DeptScopeDataInterceptor(MybatisPlusInterceptor mybatisPlusInterceptor) {
        mybatisPlusInterceptor.addInnerInterceptor(this);
    }

    public String getCreateByField() {
        return UserActionValueFillInterceptor.CREATE_BY;
    }

    public void addTableName(String tableName) {
        List<Function<Table, Expression>> list = new ArrayList<Function<Table, Expression>>();
        list.add((table) -> {
            LoginInfoVO loginInfoVO;
            try {
                loginInfoVO = LoginInfoContext.getLoginInfo();
            } catch (Exception e) {
                return null;
            }
            Set<String> userIds = loginInfoVO.getDataScopeUserIds();
            if (userIds == null || userIds.isEmpty()) {
                return null; // 返回null表示不会追加查询条件，数据权限全放开了
            }
            InExpression inExpression = new InExpression();
            inExpression.setLeftExpression(getAliasColumn(table, getCreateByField()));
            ExpressionList expressionList = new ExpressionList();
            for (String userId : userIds) {
                expressionList.addExpressions(new StringValue(userId));
            }
            inExpression.setRightItemsList(expressionList);
            return inExpression;
        });
        addTableExpressionList(tableName, list);
    }
    
    protected Column getAliasColumn(Table table, String columnName) {
        StringBuilder column = new StringBuilder();
        // 禁止 `为了兼容隐式内连接，没有别名时条件就需要加上表名`
        // 该起别名就要起别名
        if (table.getAlias() != null) {
            column.append(table.getAlias().getName());
        } else {
            column.append(table.getName());
        }
        column.append(StringPool.DOT).append(columnName);
        return new Column(column.toString());
    }
}
